package com.xfc.quartz.task;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xfc.common.core.domain.AjaxResult;
import com.xfc.common.utils.DateUtils;
import com.xfc.school.domain.ScCourse;
import com.xfc.school.domain.ScCourseList;
import com.xfc.school.domain.ScCourseSchedule;
import com.xfc.school.service.IScCourseListService;
import com.xfc.school.service.IScCourseScheduleService;
import com.xfc.school.service.IScCourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 定时任务调度自动排课
 * @author xfc
 */
@Slf4j
@Component("pxTask")
public class PxTask {


    @Autowired
    private IScCourseListService courseListService;

    @Autowired
    private IScCourseScheduleService courseScheduleService;

    public void pxCourse(){
        log.info("定时生成课程开始:{}", DateUtil.now());
        //获取本天星期几
        int week= DateUtils.getDayWeek();
        //查询最后时间的课程和周数
        QueryWrapper<ScCourseList> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.eq("week",week);
        queryWrapper2.eq("course_type",0);
        List<ScCourseList> list=courseListService.list(queryWrapper2);
        list.forEach(l->{
            //获取课程的最后时间
            QueryWrapper<ScCourseSchedule> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("course_list_id",l.getId());
            queryWrapper.orderByDesc("start_time");
            queryWrapper.last("limit 1");
            ScCourseSchedule courseSchedule=courseScheduleService.getOne(queryWrapper);
            if (Objects.nonNull(courseSchedule)){
                //新生成一周数据
                ScCourseSchedule courseSchedule1=new ScCourseSchedule();
                courseSchedule1.setCourseListId(l.getId());
                courseSchedule1.setCourseNumber(courseSchedule.getCourseNumber());
                courseSchedule1.setTeacherNumber(courseSchedule.getTeacherNumber());
                courseSchedule1.setCourseState(0);
                courseSchedule1.setCreateTime(new Date());
                //开始时间
                courseSchedule1.setStartTime(DateUtil.offsetWeek(courseSchedule.getStartTime(),1));
                //结束时间
                courseSchedule1.setEndTime(DateUtil.offsetWeek(courseSchedule.getEndTime(),1));
                courseScheduleService.save(courseSchedule1);
                log.error("课程{}",l.getCourseName(),"生成时间：{}",courseSchedule1.getStartTime(),"~",courseSchedule1.getEndTime());
            }else {
                log.error("没有查询到sc_course_schedule表数据");
            }
        });
        log.info("定时生成课程结束:{}", DateUtil.now());
    }
}
